package club.qwertyzzz;

import javax.sound.sampled.*;
import java.applet.Applet;
import java.applet.AudioClip;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 控制声音的播放
 */
public class Audio extends Thread{

    private String path;


    public Audio(String path) {
        this.path = path;
    }

    @Override
    public void run() {
        playMusic();
    }

    public void playMusic(){
        try {
            AudioInputStream as = AudioSystem.getAudioInputStream(this.getClass().getClassLoader().getResourceAsStream(path));
            AudioFormat format = as.getFormat();
            SourceDataLine sdl = null;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
            sdl = (SourceDataLine) AudioSystem.getLine(info);
            sdl.open(format);
            sdl.start();
            int nBytesRead = 0;
            byte[] abData = new byte[512];
            while (nBytesRead != -1) {
                nBytesRead = as.read(abData, 0, abData.length);
                if (nBytesRead >= 0)
                    sdl.write(abData, 0, nBytesRead);
            }
            //关闭SourceDataLine
            sdl.drain();
            sdl.close();
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        Thread.currentThread();
    }
}

